package juswaypay

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

// JuswayPayUtils 聚实汇工具类
type JuswayPayUtils struct {
	config *Config
	client *http.Client
}

// NewJuswayPayUtils 创建聚实汇工具类实例
func NewJuswayPayUtils(config *Config) *JuswayPayUtils {
	return &JuswayPayUtils{
		config: config,
		client: &http.Client{
			Timeout: time.Duration(config.Timeout) * time.Second,
		},
	}
}

// IsTokenValid 检查token是否有效
func (u *JuswayPayUtils) IsTokenValid(expiresIn int64) bool {
	return time.Now().Unix() < expiresIn
}

// ShouldRefreshToken 检查是否需要刷新token
func (u *JuswayPayUtils) ShouldRefreshToken(expiresIn int64) bool {
	// 如果token已经过期，需要刷新
	if !u.IsTokenValid(expiresIn) {
		return true
	}
	// 如果token距离过期还有不到10分钟，需要刷新
	return expiresIn-time.Now().Unix() < 600
}

// GetAccessToken 获取访问令牌
func (u *JuswayPayUtils) GetAccessToken() (string, string, int, error) {
	loginData := map[string]string{
		"username": u.config.Username,
		"password": u.config.Password,
	}

	jsonData, err := json.Marshal(loginData)
	if err != nil {
		return "", "", 0, fmt.Errorf("marshal login data failed: %v", err)
	}

	reqURL := u.config.GatewayURL + "/v1/login?status"
	fmt.Printf("登录请求URL: %s\n", reqURL)
	fmt.Printf("登录请求数据: %s\n", string(jsonData))

	req, err := http.NewRequest("POST", reqURL, bytes.NewReader(jsonData))
	if err != nil {
		return "", "", 0, fmt.Errorf("create login request failed: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "*/*")
	req.Header.Set("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
	req.Header.Set("Connection", "keep-alive")

	resp, err := u.client.Do(req)
	if err != nil {
		return "", "", 0, fmt.Errorf("do login request failed: %v", err)
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", "", 0, fmt.Errorf("read login response failed: %v", err)
	}

	fmt.Printf("登录响应数据: %s\n", string(respBody))

	var loginResp LoginResponse
	if err := json.Unmarshal(respBody, &loginResp); err != nil {
		return "", "", 0, fmt.Errorf("unmarshal login response failed: %v", err)
	}

	if !loginResp.Ret {
		return "", "", 0, fmt.Errorf("login failed: status=%d", loginResp.Status)
	}

	return loginResp.Data.AccessToken, loginResp.Data.TokenType, loginResp.Data.ExpiresIn, nil
}

// RefreshAccessToken 刷新访问令牌
func (u *JuswayPayUtils) RefreshAccessToken(currentToken string) (string, string, int, error) {
	reqURL := u.config.GatewayURL + "/v1/refresh/token"
	fmt.Printf("刷新token请求URL: %s\n", reqURL)

	req, err := http.NewRequest("POST", reqURL, nil)
	if err != nil {
		return "", "", 0, fmt.Errorf("create refresh token request failed: %v", err)
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+currentToken)
	req.Header.Set("Accept", "*/*")
	req.Header.Set("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
	req.Header.Set("Connection", "keep-alive")

	resp, err := u.client.Do(req)
	if err != nil {
		return "", "", 0, fmt.Errorf("do refresh token request failed: %v", err)
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", "", 0, fmt.Errorf("read refresh token response failed: %v", err)
	}

	fmt.Printf("刷新token响应数据: %s\n", string(respBody))

	var refreshResp LoginResponse
	if err := json.Unmarshal(respBody, &refreshResp); err != nil {
		return "", "", 0, fmt.Errorf("unmarshal refresh token response failed: %v", err)
	}

	if !refreshResp.Ret {
		return "", "", 0, fmt.Errorf("refresh token failed: status=%d", refreshResp.Status)
	}

	return refreshResp.Data.AccessToken, refreshResp.Data.TokenType, refreshResp.Data.ExpiresIn, nil
}
